var OBJi={};
var dizhiaa=""
var idufoijgo=""
var kjshadkj=""
var paymentMethodalls=""
var customerCode = getQueryString('id');
var customerId = getQueryString('customerId');
//发货仓
deliverywarehouseulfn();
function deliverywarehouseulfn(){
    var lihtmlone='';
    var lihtml='';
    var canghuixiancode =$("#warehouseId").attr('cangcode');
    var canghuixianhtml =$("#warehouseId").attr('cangname');
    var provincehuixiancode =$("#warehouseId").attr('provincecode');
    var provincehuixianame =$("#warehouseId").attr('provincename');
    $("#deliverywarehouseul").val('')
    $.ajax({
        url: root.publics.getAllWarehouse,
        cache: false, //禁用缓存
        type: "POST",
        dataType:"json",
        data:{},
        success: function(data){
            if (data.errorCode == 0){
                console.log('777777我是发货仓数据')
                console.log(data.data)
                
                if(data.data.length >0){
                    if(canghuixiancode == ""){
                        $("#deliverywarehouseul").attr('porvincode',provincehuixiancode)
                        $("#deliverywarehouseul").attr('porvinname',provincehuixianame)
                        lihtmlone += '<option value="" code=""  selected name="平行仓">平行仓</option>'
                        $("#deliverywarehouseul").val('')
                        $.each(data.data,function(i,item){
                            if(item.warehouse_data_type !=2){
             
                                    lihtml+='<option value="'+item.warehouse_code+'"  noprovincename="'+item.provinceName+'"  noprovincecode="'+item.provinceCode+'" >'+item.warehouse_name+'</option>'
                                 
                            }
                        })
                    }else{
                        $("#deliverywarehouseul").attr('porvincode',provincehuixiancode)
                        $("#deliverywarehouseul").attr('porvinname',provincehuixianame)
                        $("#deliverywarehouseul").attr('code',canghuixiancode)
                        $("#deliverywarehouseul").attr('name',canghuixianhtml)
                        $(".linkagebox").addClass('hide')
                        $(".nolinkagebox").removeClass('hide')
                        $(".nolinkagebox").html(provincehuixianame)
                     
                        $.each(data.data,function(i,item){
                            if(canghuixiancode == item.warehouse_code){
                                $("#deliverywarehouseul").attr('code',canghuixiancode)
                                $("#deliverywarehouseul").attr('name',canghuixianhtml)
                                $("#deliverywarehouseul").val(item.warehouse_code)
                            }
                        }) 
                        lihtmlone += '<option value="" code=""   name="平行仓">平行仓</option>'
                        $.each(data.data,function(i,item){
                            if(item.warehouse_data_type !=2){
                                if(provincehuixiancode == item.provinceCode){
                                    lihtml+='<option value="'+item.warehouse_code+'" noprovincename="'+item.provinceName+'"  noprovincecode="'+item.provinceCode+'" selected>'+item.warehouse_name+'</option>'
                                }else{
                                    lihtml+='<option value="'+item.warehouse_code+'"  noprovincename="'+item.provinceName+'"  noprovincecode="'+item.provinceCode+'" >'+item.warehouse_name+'</option>'
                                } 
                            }
                        })
                    }

                    $("#deliverywarehouseul").html(lihtmlone+lihtml)
                }
            } else{
                layer.msg(data.errorMessage, {icon: 5,time:2000});
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });
};
function wherehouseChange(){
    var option =$("#deliverywarehouseul option:selected");
    console.log(option.attr('noprovincecode'))
    console.log(option.attr('noprovincename'))
    $("#deliverywarehouseul").attr('code',option.val())
    $("#deliverywarehouseul").attr('name',option.html())
    if(option.val() == ""){//平行仓 主价格省份可以下拉搜索
        $(".linkagebox").removeClass('hide')
        $(".nolinkagebox").addClass('hide')
        $("#fen_lsit22").html('')
        $("#fen_lsit22").attr('porvincode','')
        $("#fen_lsit22").attr('porvinname','')
    }else{
        $(".linkagebox").addClass('hide')
        $(".nolinkagebox").removeClass('hide')
        $(".nolinkagebox").html(option.attr('noprovincename')) 
        $("#deliverywarehouseul").attr('porvinname',option.attr('noprovincename')) 
        $("#deliverywarehouseul").attr('porvincode',option.attr('noprovincecode')) 
        $("#fen_lsit22").html('')
    }
}
//主价格省份
    dongtai()
    function dongtai(keyword) {
        $.ajax({
            contentType: "application/json;charset=UTF-8",
            url:root.sroreinter.getAddressByMainAddressList,
            cache: false, //禁用缓存
            type: "POST",
            dataType:"json",
            async:false,//优先运行
            data: JSON.stringify({
                addressCode:"",
                addressCodes:[],
                parentAddressCode:"",
                parentAddressCodes:[],
                addressLevels:['101'],
                addressNameLike:keyword,//模糊搜索关键字
                pageSize:1000,
                pageNum:1
            }),
            success: function (data) {
                console.log('我是省份777777777')
                console.log(data)
                var optionstring = "";
                var pingjia="";
                var pingjiahtml='平行价格'
                if(data.data.length >0){
                    pingjia="<li class='quyuss' onclick='addCodeFun22(0,\""+ pingjiahtml+ "\")'>平行价格</li>"
                    $("#getArea").removeClass('hide')
                    for(var i=0;i<data.data.length;i++){
                        optionstring += "<li class='quyuss' onclick='addCodeFun22("+  data.data[i].code+ ",\""+ data.data[i].name+ "\")'>"+ data.data[i].name+ "</li>";
    
                        $("#getArea").html(pingjia+optionstring);
                    }
                }else{
                    
                    $("#getArea").html('暂无数据');
                    $("#getArea").removeClass('hide')
                    $("#deliverywarehouseul").attr('porvincode','')
                    $("#deliverywarehouseul").attr('porvinname','')
                }

            },
            error: function () {
                $.Huimodalalert('失败！',2000);
            }
        });
    };
    $("#fen_lsit22").on('click',function(i,item){
        $("#getArea").removeClass('hide')  
    })
    $(document).bind("click",function(e){
        if($(e.target).closest("#getArea").length == 0 && $(e.target).closest("#fen_lsit22").length == 0){
            $("#getArea").addClass('hide')
        }
    })
    function addCodeFun22(id,brand_name) {
        $("#getArea").addClass('hide');
        $("#fen_lsit22").html(brand_name)
        $("#deliverywarehouseul").attr('porvincode',id)
        $("#deliverywarehouseul").attr('porvinname',brand_name)
    };
function seachprovicnsfn(e){
    dongtai($(e).html())
}
$("[name='scene']").click(function () { //多选框点击选中
    insertChangeInfo();
});

function insertChangeInfo() { //保存客户相关设置信息
    var id =getQueryString('id');
    var customerId = getQueryString('customerId');
    var scenes = document.getElementsByName("scene");
    var scenesList = [];
    for(k in scenes){
        if (scenes[k].checked){

            if(scenes[k].value!=undefined){
                scenesList.push(scenes[k].value);
            }

        }
    }
    var typeAll = "";
    for (var i=0;i<scenesList.length;i++){
        typeAll += scenesList[i]+",";
    }
    var warehouseCode = $("#warehouseId").val();
    var warehouseName = $("#warehouseCode22").text();
    var limitType = $("#limieId").val();
    var joinActivity = $("#joinActivityCode").val();
    var priceTypeid = "";
    if($("#priceType").html()=="售价"){
        priceTypeid = "10"
    }else if($("#priceType").html()=="批发价"){
        priceTypeid = "20"
    }else if($("#priceType").html()=="分销批发价"){
        priceTypeid = "30"
    }else if($("#priceType").html()=="成本价"){
        priceTypeid = "40"
    }

    //支付方式
    var paymentmethods = document.getElementsByName("paymentmethod");
    var paymentmethodList = [];
    for(k in paymentmethods){
        if (paymentmethods[k].checked){
            if(paymentmethods[k].value!=undefined){
                paymentmethodList.push(paymentmethods[k].value);
            }

        }
    }
    var paymentmethodAll = "";
    for (var i=0;i<paymentmethodList.length;i++){
        paymentmethodAll += paymentmethodList[i]+",";
    }
    if (paymentmethodAll.length > 0) {
        paymentmethodAll = paymentmethodAll.substr(0, paymentmethodAll.length - 1);
    }
    $.ajax({
        url: root.sroreinter.insertCustomerSetupInfo,//'https://'+ window.location.host +'/api/admin/acontract/customerExt/insertCustomerSetupInfo.jhtml',
        /*url: 'https://www.fsyuncai.com/api/admin/acontract/customerExt/insertCustomerSetupInfo.jhtml',*/
        cache: false, //禁用缓存
        type: "POST",
        dataType:"json",
        data:{
            limitType:limitType,
            warehouseCode:warehouseCode,
            warehouseName:warehouseName,
            customerScene:typeAll,
            customerId:customerId,
            customerCode:id,
            joinActivity:joinActivity,
            priceType:priceTypeid,
            paymentMethod:paymentmethodAll,
        },
        success: function(obj){
            if(obj.sub_code == 0){
                layer.msg(obj.sub_msg, {
                    icon: 1,
                    time: 1000
                }, function() {
                    location.replace(location.href)
                });

            }else{
                layer.msg(obj.sub_msg, {icon: 5,time:2000});
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });
}

function getCustomerSetting() { //回显内容
    var id =getQueryString('id');
    var customerId = getQueryString('customerId');
    $.ajax({
        url: root.member.getCustomerSetupByCode,
        cache: false, //禁用缓存
        type: "POST",
        dataType:"json",
        data:{customerCode:id},
        success: function(obj){
            OBJi=obj;
            if(obj.sub_code == 0){
                var data = obj.data;
                if (data != null) {
                    var scenes = document.getElementsByName("scene");
                    if (data.customerScene != ""&&data.customerScene != null) {
                        var sceneList = data.customerScene.split(",");
                        for (k in scenes) {
                            for (var i = 0; i < sceneList.length; i++) {
                                if (scenes[k].value == sceneList[i]) {
                                    scenes[k].checked = true;
                                }
                            }
                        }
                    }
                    if (data.warehouseName != ""&&data.warehouseName !=null) {
                        $("#warehouseCode22").text(data.warehouseName);
                        $("#warehouseId").val(data.warehouseCode);
                            $("#warehouseId").attr('provinceCode',data.provinceCode==''?0:data.provinceCode);
                            $("#warehouseId").attr('provincename',data.provinceName);
                            $("#pricecity").html(data.provinceName)  
                        $("#warehouseId").attr('cangname',data.warehouseName);
                        $("#warehouseId").attr('cangcode',data.warehouseCode);
                    
                    }
                    $("#provinceName").html(data.provinceName)

                /*    if(data.limitType==null||data.limitType==0){
                        $("#limitMoney").text("")
                        $("#limieId").val("");
                    }else {
                        $("#limieId").val(data.limitType);
                        if (data.limitType == 10) {
                            $("#limitMoney").text('不限制货到付款')
                        } else  if (data.limitType == 20){
                            $("#limitMoney").text('限制货到付款')
                        }
                    }*/



                    paymentMethodalls=data.paymentMethod
                    var paymentMethods = document.getElementsByName("paymentmethod");
                    if (data.paymentMethod != ""&&data.paymentMethod != null) {
                        var paymentMethodList = data.paymentMethod.split(",");
                        for (k in paymentMethods) {
                            for (var i = 0; i < paymentMethodList.length; i++) {
                                if (paymentMethods[k].value == paymentMethodList[i]) {
                                    paymentMethods[k].checked = true;
                                }
                            }
                        }
                    }else {
                        for (k in paymentMethods) {

                                    paymentMethods[k].checked = true;

                        }
                    }
                    console.log(data)


                   //运费设置
                    if(sessionStorage.getItem("customertype")=='商店'){
                        if(data.freightRule!=null&&data.freightRule!=""){
                            if(data.freightRule==10){
                                $("#joinActivsity").text("收取运费")
                            }else if(data.freightRule==20){
                                $("#joinActivsity").text("免运费")
                            }else if(data.freightRule==30){
                                $("#joinActivsity").text("阶梯运费")
                            }else if(data.freightRule==40){
                                $("#joinActivsity").text("平台免运费政策")
                            }
                        }else {
                            $("#joinActivsity").text("免运费")
                        }

                    }else {
                        if(data.freightRule!=null&&data.freightRule!=""){
                            if(data.freightRule==10){
                                $("#joinActivsity").text("收取运费")
                            }else if(data.freightRule==20){
                                $("#joinActivsity").text("免运费")
                            }else if(data.freightRule==30){
                                $("#joinActivsity").text("阶梯运费")
                            }else if(data.freightRule==40){
                                $("#joinActivsity").text("平台免运费政策")
                            }
                        }else {
                            $("#joinActivsity").text("收取运费")
                        }
                    }

                    if(sessionStorage.getItem("customertype")=='商店'){

                        $("#priceTypexg").css({
                            display: "inline"
                        });
                        $("#priceTypejl").css({
                            display: "inline"
                        });
                        if(data.priceType !=null){
                            if(data.priceType == 10){
                                $("#priceType").text('售价')
                            }else if(data.priceType == 20){
                                $("#priceType").text('批发价')
                            }else if(data.priceType == 30){
                                $("#priceType").text('分销批发价')
                            }else if(data.priceType == 40){
                                $("#priceType").text('成本价')
                            }
                        }else {
                            $("#priceType").text('')
                        }
                    }else {
                        $("#priceTypexg").css({
                            display: "inline"
                        });
                        $("#priceTypejl").css({
                            display: "inline"
                        });
                        if(data.priceType !=null){
                        if(data.priceType == 10){
                            $("#priceType").text('售价')
                        }else if(data.priceType == 20){
                            $("#priceType").text('批发价')
                        }else if(data.priceType == 30){
                            $("#priceType").text('分销批发价')
                        }else if(data.priceType == 40){
                            $("#priceType").text('成本价')
                        }
                        }else {
                            $("#priceType").text('')
                        }

                    }
                    if (data.joinActivity == 10){
                        $("#joinActivity").text("可以参加");
                        $("#joinActivityCode").val("10");
                    }else {
                        $("#joinActivity").text("不可参加");
                        $("#joinActivityCode").val("20");
                    }

                } else {
                    if(sessionStorage.getItem("customertype")=='商店'){

                        $("#priceType").text('分销批发价')
                        $("#priceTypexg").css({
                            display: "inline"
                        });
                        $("#priceTypejl").css({
                            display: "inline"
                        });
                    }else {
                        $("#priceType").text('批发价')
                        $("#priceTypexg").css({
                            display: "inline"
                        });
                        $("#priceTypejl").css({
                            display: "inline"
                        });


                    }
                }
                getInvoice();
                getInvoicecrm()
            }else{
                layer.msg(obj.sub_msg, {icon: 5,time:2000});
            }

            //是否带回显示
            console.log(obj.data.needReceipt);
            $("input[name='needReceipt']").prop("checked",false);
            if (obj.data.needReceipt == 0) {
                $("#needReceipt-no").prop("checked",true);
            }else{
                $("#needReceipt-yes").prop("checked",true);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });
}
function close_model(type) { //关闭弹框
  if(type ==2){
        $("#company1").modal("hide");
    }else if(type ==3){
        $("#phos1").modal("hide");
    }else if(type ==1){
        $("#pricitybox").modal("hide")
    }else if(type ==4){
        $("#join-activity").modal("hide")
    }else if(type ==5){
      $("#company").modal("hide");
  }

}
function warehouseUpdate(title,type) { //修改 发货仓 或者 限制货到付款
    var id = getQueryString('id');
    if(type == 1){
        var index = layer.open({
            type: 2,
            title: title,
            content:'servicerecord.html?id='+id
        });
        layer.full(index);
    }else if(type == 3){
        var index = layer.open({
            type: 2,
            title: title,
            content:'price_type.html?id='+id
        });
        layer.full(index);
    }else if(type == 2){
        var index = layer.open({
            type: 2,
            title: title,
            content: 'servicerecord_limit.html?id='+id
        });
        layer.full(index);
    }

}
function saveInvoice() {  //保存发票信息
    var customerId = getQueryString('customerId');
    var id = getQueryString('id');
    var organizationName = $("#name").val();
    var taxpayerCode = $("#code").val();
    var registeredAddress = $("#address").val();
    var registeredPhone = $("#phone").val();
    var openingBank = $("#bank").val();
    var bankAccount = $("#bankNumber").val();
    if(organizationName == "") {
        layer.msg('请填写单位名称', {icon: 5, time: 2000});
        return false;
    }

    if(taxpayerCode == "") {
        layer.msg('请填写纳税人识别号', {icon: 5, time: 2000});
        return false;
    }else{
        var sccess = checkedTaxpayerCode(taxpayerCode);
        if(!sccess){
            return;
        };
    }

    if(registeredAddress == "") {
        layer.msg('请填写注册地址', {icon: 5, time: 2000});
        return false;
    }

    if(registeredPhone == "") {
        layer.msg('请填写注册电话', {icon: 5, time: 2000});
        return false;
    }
    /*var mobile = /^1[3|5|8]\d{9}$/ , phone = /^0\d{2,3}-?\d{7,8}$/;
    if( !mobile.test(registeredPhone) && !phone.test(registeredPhone)){
        layer.msg('注册电话格式错误', {icon: 5, time: 2000});
        return false;
    }*/
    if(registeredPhone.length < 0 || registeredPhone.length > 50) {
        layer.msg('注册电话长度必须在0到50之间', {icon: 5, time: 2000});
        return false;
    }


    if(openingBank == "") {
        layer.msg('请填写开户银行', {icon: 5, time: 2000});
        return false;
    }

    if(bankAccount == "") {
        layer.msg('请填写银行帐号', {icon: 5, time: 2000});
        return false;
    }
    $.ajax({
        url: 'https://'+ window.location.host +'/api/admin/acontract/invoice/insertInvoice.jhtml',
        cache: false, //禁用缓存
        type: "POST",
        dataType: "json",
        data: {
            customerId: customerId,
            customerCode:id,
            organizationName:organizationName,
            taxpayerCode:taxpayerCode,
            registeredAddress:registeredAddress,
            registeredPhone:registeredPhone,
            openingBank:openingBank,
            bankAccount:bankAccount
        },
        success: function (obj) {
            if (obj.sub_code == 0) {
                layer.msg(obj.sub_msg, {
                    icon: 1,
                    time: 1000,
                    end: function () {
                        $("#invoiceInfo").show();
                        $("#invoiceSave").hide();
                        $("#invoice_info .canEdit").attr("disabled",true);
                    }
                });

            } else {
                layer.msg(obj.sub_msg, {icon: 5, time: 2000});
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });
}


function checkedTaxpayerCode(taxpayerId){  //校验纳税人识别号
    //纳税人识别号校验是否合法
    if($.trim(taxpayerId) != ''){
        var addressCode = taxpayerId.substring(0,6);
        // 校验地址码
        var check = checkAddressCode(addressCode);
        if(!check) {
            layer.msg('请输入正确的纳税人识别号 (地址码)！', {icon: 5, time: 2000});
            return false;
        }else{
            // 校验组织机构代码
            var orgCode = taxpayerId.substring(6,9);
            check = orgcodevalidate(orgCode);
            if(!check){
                layer.msg('请输入正确的纳税人识别号 (组织机构代码)！', {icon: 5, time: 2000});
                return false;
            }
        }
        return true;
    }
    // 校验组织机构代码
    function orgcodevalidate(value){
        if(value!=""){
            var part1=value.substring(0,8);
            var part2=value.substring(value.length-1,1);
            var ws = [3, 7, 9, 10, 5, 8, 4, 2];
            var str = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            var reg = /^([0-9A-Z]){8}$/;
            if (!reg.test(part1))
            {
                return true
            }
            var sum = 0;
            for (var i = 0; i< 8; i++)
            {
                sum += str.indexOf(part1.charAt(i)) * ws[i];
            }
            var C9 = 11 - (sum % 11);
            var YC9=part2+'';
            if (C9 == 11) {
                C9 = '0';
            } else if (C9 == 10) {
                C9 = 'X' ;
            } else {
                C9 = C9+'';
            }
            return YC9!=C9;
        }
    }

    // 校验地址码
    function checkAddressCode(addressCode){
        var provinceAndCitys={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",
            31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",
            45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",
            65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外",92:"北京"};
        var check = /^[1-9]\d{5}$/.test(addressCode);
        if(!check) return false;
        if(provinceAndCitys[parseInt(addressCode.substring(0,2))]){
            return true;
        }else{
            return false;
        }

    }
}



function save_edit1(type) { //保存弹框选中内容
    console.log(1111777777)
    var id = getQueryString('id');
    var loginData = JSON.parse(web.readCookie("loginData"));
    var createUser = loginData.user.name; //创建人
    if (type == 1) {
        if(!$("#fen_lsit22").html() && $('.nolinkagebox').hasClass('hide')){
                layer.msg('请选择指定省份', {icon: 5, time: 2000});
                return;
        }
        if ($("#dcTextArea5").val() == "") {
            layer.msg('备注不能为空', {icon: 5, time: 2000});
            return;
        }
        if ($("#dcTextArea5").val().length > 200) {
            layer.msg('长度太长', {icon: 5, time: 2000});
            return;
        }
        var id =getQueryString('id');
        var customerId = getQueryString('customerId');
        var scenes = document.getElementsByName("scene");
        var scenesList = [];
        for(k in scenes){
            if (scenes[k].checked){
                if(scenes[k].value!=undefined){
                    scenesList.push(scenes[k].value);
                }

            }
        }
        var typeAll = "";
        for (var i=0;i<scenesList.length;i++){
            typeAll += scenesList[i]+",";
        }
        var warehouseCode =$("#deliverywarehouseul").attr('code');
        var warehouseName = $("#deliverywarehouseul").attr('name')
        var limitType = $("#limieId").val();
        var joinActivity = $("#joinActivityCode").val();
        var priceTypeid = "";
        if($("#priceType").html()=="售价"){
            priceTypeid = "10"
        }else if($("#priceType").html()=="批发价"){
            priceTypeid = "20"
        }else if($("#priceType").html()=="分销批发价"){
            priceTypeid = "30"
        }else if($("#priceType").html()=="成本价"){
            priceTypeid = "40"
        }

        //支付方式
        var paymentmethods = document.getElementsByName("paymentmethod");
        var paymentmethodList = [];
        for(k in paymentmethods){
            if (paymentmethods[k].checked){
                if(paymentmethods[k].value!=undefined){
                    paymentmethodList.push(paymentmethods[k].value);
                }

            }
        }
        var paymentmethodAll = "";
        for (var i=0;i<paymentmethodList.length;i++){
            paymentmethodAll += paymentmethodList[i]+",";
        }
        if (paymentmethodAll.length > 0) {
            paymentmethodAll = paymentmethodAll.substr(0, paymentmethodAll.length - 1);
        }
        if($("#deliverywarehouseul").attr('porvincode') ==""){
            layer.msg('请选择正确的省份', {icon: 5, time: 2000});
            return; 
        }
        $.ajax({
            url:root.sroreinter.insertCustomerSetupInfo,// 'https://'+ window.location.host +'/api/admin/acontract/customerExt/insertCustomerSetupInfo.jhtml',
            cache: false, //禁用缓存
            type: "POST",
            dataType:"json",
            data:{
                limitType:limitType,
                warehouseCode:warehouseCode,
                warehouseName:warehouseName,
                customerScene:typeAll,
                customerId:customerId,
                customerCode:id,
                joinActivity:joinActivity,
                priceType:priceTypeid,
                paymentMethod:paymentmethodAll,
                provinceCode:$("#deliverywarehouseul").attr('porvincode')==0?'':$("#deliverywarehouseul").attr('porvincode'),
                provinceName:$("#deliverywarehouseul").attr('porvinname'),
            },
            success: function(obj){
                if(obj.sub_code == 0){
                    layer.msg(obj.sub_msg, {
                        icon: 1,
                        time: 1000
                    }, function() {
                        var namecang = $("#deliverywarehouseul").attr('name');
                        var nameporvinc = $("#deliverywarehouseul").attr('porvinname');
                        var text = $("#dcTextArea5").val();
                        var oldwarehouseName = $("#warehouseCode22").html();
                        var oldpricecity=$("#pricecity").html();
                        $.ajax({
                            url:root.sroreinter.insertChangeInfo ,//'https://'+ window.location.host +'/api/admin/acontract/customerExt/insertChangeInfo.jhtml',
                            cache: false, //禁用缓存
                            type: "POST",
                            dataType: "json",
                            data: {
                                originalValue:'发货仓='+ oldwarehouseName+',价格省份='+oldpricecity,
                                changeValue: '发货仓='+namecang+',价格省份='+nameporvinc,
                                changeUser: createUser,
                                remarks: text,
                                changeType: 10,
                                customerCode: id,
                            },
                            success: function (obj) {
                                if (obj.sub_code == 0) {
                                    layer.msg(obj.sub_msg, {
                                        icon: 1,
                                        time: 1000,
                                        end: function () {
                                            $("#pricitybox").modal("hide");
                                            getCustomerSetting();
                                            // setTimeout(function(){
                                            //     location.replace(location.href)
                                            // },1000);

                                        }
                                    });
                                } else {
                                    layer.msg(obj.sub_msg, {icon: 5, time: 2000});
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                alert(XMLHttpRequest);
                            }
                        });
                    });

                }else{
                    layer.msg(obj.sub_msg, {icon: 5,time:2000});
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest);
            }
        });

    } else if (type == 2) {
        if ($("#limitText").val() == "") {
            layer.msg('备注不能为空', {icon: 5, time: 2000});
            return;
        }
        if ($("#limitText").val().length > 200) {
            layer.msg('长度太长', {icon: 5, time: 2000});
            return;
        }
        var limitId = $("input[name='cashonDelivery']:checked").val();
        var limitName = $("input[name='cashonDelivery']:checked").next();
        var name = $(limitName).text();
        var text = $("#limitText").val();
        var oldlimitName = $("#limitMoney").text();
        $.ajax({
            url:root.sroreinter.insertChangeInfo,// 'https://'+ window.location.host +'/api/admin/acontract/customerExt/insertChangeInfo.jhtml',
            cache: false, //禁用缓存
            type: "POST",
            dataType: "json",
            data: {
                originalValue: oldlimitName,
                changeValue: name,
                changeUser: createUser,
                remarks: text,
                changeType: 20,
                customerCode: id,
            },
            success: function (obj) {
                if (obj.sub_code == 0) {
                    layer.msg(obj.sub_msg, {
                        icon: 1,
                        time: 1000,
                        end: function () {
                            $("#limitMoney").text(name);
                            $("#limieId").val(limitId);
                            insertChangeInfo();
                            $("#company1").modal("hide");
                        }
                    });
                } else {
                    layer.msg(obj.sub_msg, {icon: 5, time: 2000});
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest);
            }
        });


    } else if (type == 3) {
        if ($("#pachText").val() == "") {
            layer.msg('备注不能为空', {icon: 5, time: 2000});
            return;
        }
        if ($("#pachText").val().length > 200) {
            layer.msg('长度太长', {icon: 5, time: 2000});
            return;
        }
        var limitId = $("input[name='priceTypeidivery']:checked").val();
        var limitName = $("input[name='priceTypeidivery']:checked").next();
        var name = $(limitName).text();
        var text = $("#pachText").val();
        var oldlimitName = $("#priceType").text();
        $.ajax({
            url: root.sroreinter.insertChangeInfo,//'https://'+ window.location.host +'/api/admin/acontract/customerExt/insertChangeInfo.jhtml',
            cache: false, //禁用缓存
            type: "POST",
            dataType: "json",
            data: {
                originalValue: oldlimitName,
                changeValue: name,
                changeUser: createUser,
                remarks: text,
                changeType: 30,
                customerCode: id,
            },
            success: function (obj) {
                if (obj.sub_code == 0) {
                    layer.msg(obj.sub_msg, {
                        icon: 1,
                        time: 1000,
                        end: function () {
                            $("#priceType").text(name);
                            $("#priceId").val(limitId);
                            insertChangeInfo();
                            $("#phos1").modal("hide");
                        }
                    });
                } else {
                    layer.msg(obj.sub_msg, {icon: 5, time: 2000});
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest);
            }
        });


    }else if (type == 4) {
        insertChangeInfo();
        $("#join-activity").modal("hide");
        var joinActivity = $("#joinActivityCode").val();
        if (10 == joinActivity) {
            $("#joinActivity").text("可以参加");
            $("#joinActivityCode").val(10);
        } else {
            $("#joinActivity").text("不可参加");
            $("#joinActivityCode").val(20);
        }

    }else if(type == 5){
        if ($("#dcTextArea").val() == "") {
            layer.msg('备注不能为空', {icon: 5, time: 2000});
            return;
        }
        if ($("#dcTextArea").val().length > 200) {
            layer.msg('长度太长', {icon: 5, time: 2000});
            return;
        }
        var id =getQueryString('id');
        var customerId = getQueryString('customerId');
        var scenes = document.getElementsByName("scene");
        var scenesList = [];
        for(k in scenes){
            if (scenes[k].checked){

                if(scenes[k].value!=undefined){
                    scenesList.push(scenes[k].value);
                }

            }
        }
        var typeAll = "";
        for (var i=0;i<scenesList.length;i++){
            typeAll += scenesList[i]+",";
        }
        // var warehouseCode = $("#warehouseId").val();
        // var warehouseName = $("#warehouseCode").text();
        var warehouseCode = $("input[name='cityDC']:checked").val();
        var warehouseName = $("input[name='cityDC']:checked").next().html()
        var limitType = $("#limieId").val();
        var joinActivity = $("#joinActivityCode").val();
        var priceTypeid = "";
        if($("#priceType").html()=="售价"){
            priceTypeid = "10"
        }else if($("#priceType").html()=="批发价"){
            priceTypeid = "20"
        }else if($("#priceType").html()=="分销批发价"){
            priceTypeid = "30"
        }else if($("#priceType").html()=="成本价"){
            priceTypeid = "40"
        }

        //支付方式
        var paymentmethods = document.getElementsByName("paymentmethod");
        var paymentmethodList = [];
        for(k in paymentmethods){
            if (paymentmethods[k].checked){
                if(paymentmethods[k].value!=undefined){
                    paymentmethodList.push(paymentmethods[k].value);
                }

            }
        }
        var paymentmethodAll = "";
        for (var i=0;i<paymentmethodList.length;i++){
            paymentmethodAll += paymentmethodList[i]+",";
        }
        if (paymentmethodAll.length > 0) {
            paymentmethodAll = paymentmethodAll.substr(0, paymentmethodAll.length - 1);
        }
        $.ajax({
            url: 'https://'+ window.location.host +'/api/admin/acontract/customerExt/insertCustomerSetupInfo.jhtml',
            cache: false, //禁用缓存
            type: "POST",
            dataType:"json",
            data:{
                limitType:limitType,
                warehouseCode:warehouseCode,
                warehouseName:warehouseName,
                customerScene:typeAll,
                customerId:customerId,
                customerCode:id,
                joinActivity:joinActivity,
                priceType:priceTypeid,
                paymentMethod:paymentmethodAll,
            },
            success: function(obj){
                if(obj.sub_code == 0){
                    console.log(777777777)
                    layer.msg(obj.sub_msg, {
                        icon: 1,
                        time: 1000
                    }, function() {

                        var cityDcId = $("input[name='cityDC']:checked").val();
                        var cityDcName = $("input[name='cityDC']:checked").next();
                        var name = $(cityDcName).text();
                        var text = $("#dcTextArea").val();
                        var oldwarehouseName = $("#warehouseCode").text();
                        $.ajax({
                            url: 'https://'+ window.location.host +'/api/admin/acontract/customerExt/insertChangeInfo.jhtml',
                            cache: false, //禁用缓存
                            type: "POST",
                            dataType: "json",
                            data: {
                                originalValue: oldwarehouseName,
                                changeValue: name,
                                changeUser: createUser,
                                remarks: text,
                                changeType: 10,
                                customerCode: id,
                            },
                            success: function (obj) {
                                if (obj.sub_code == 0) {
                                    layer.msg(obj.sub_msg, {
                                        icon: 1,
                                        time: 1000,
                                        end: function () {

                                            $("#warehouseCode").text(name);
                                            $("#warehouseId").val(cityDcId);
                                            $("#company").modal("hide");
                                            setTimeout(function(){
                                                location.replace(location.href)
                                            },1000);

                                        }
                                    });
                                } else {
                                    layer.msg(obj.sub_msg, {icon: 5, time: 2000});
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                alert(XMLHttpRequest);
                            }
                        });
                    });

                }else{
                    layer.msg(obj.sub_msg, {icon: 5,time:2000});
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest);
            }
        });
     
    }
}
function attrprovincitycodefn(provinceattr,cityattr){
    $("#address_test_provinceName").attr('provinceCode',provinceattr)
    $("#address_test_cityName").attr('cityCode',cityattr)
}

function changeActivityStatus() {
    let selectActivityVal = $("#selectActivity option:selected").val();
    if (10 == selectActivityVal) {
        $("#joinActivityCode").val("10")
    }else{
        $("#joinActivityCode").val("20")
    }
}
//发票信息客服
function getInvoice() { //获取增值税专用发票发票信息
    var customerId = getQueryString('customerId');
    var getInvoice=''
    var user_data = {}
    var succCallBack = function(data, status, response) {
            if(data.data!=""){
                    for(var i=0;i<data.data.length;i++){
                        getInvoice+='<tr>\n' +
                            '                            <td class="w-300" style="background:#ececec;">单位名称</td>\n' +
                            '                            <td><input class="canEdit text-c radius box-shadow"  placeholder="请输入单位名称" value="'+data.data[i].organizationName+'" disabled/></td>\n' +
                            '                        </tr>\n' +
                            '                        <tr>\n' +
                            '                            <td style="background:#ececec">纳税人识别码</td>\n' +
                            '                            <td><input class="canEdit text-c radius box-shadow" placeholder="请输入纳税人识别码" value="'+data.data[i].taxpayerCode+'"  disabled/></td>\n' +
                            '                        </tr>\n' +
                            '                        <tr>\n' +
                            '                            <td style="background:#ececec;">注册地址</td>\n' +
                            '                            <td><input class="canEdit text-c radius box-shadow"  placeholder="请输入注册地址" value="'+data.data[i].registeredAddress+'"  disabled/></td>\n' +
                            '                        </tr>\n' +
                            '                        <tr>\n' +
                            '                            <td style="background:#ececec">注册电话</td>\n' +
                            '                            <td><input class="canEdit text-c radius box-shadow" placeholder="请输入注册电话" value="'+data.data[i].registeredPhone+'"  disabled/></td>\n' +
                            '                        </tr>\n' +
                            '                        <tr>\n' +
                            '                            <td style="background:#ececec">开户银行</td>\n' +
                            '                            <td><input class="canEdit text-c radius box-shadow" placeholder="请输入开户银行" value="'+data.data[i].openingBank+'"  disabled/></td>\n' +
                            '                        </tr>\n' +
                            '                        <tr>\n' +
                            '                            <td style="background:#ececec">银行账户</td>\n' +
                            '                            <td><input class="canEdit text-c radius box-shadow"  placeholder="请输入银行账户" value="'+data.data[i].bankAccount+'"  disabled/></td>\n' +
                            '                        </tr>'
                    }
            }else {
                getInvoice='<tr>\n' +
                    '                            <td class="w-300" style="background:#ececec;">单位名称</td>\n' +
                    '                            <td><input class="canEdit text-c radius box-shadow"  placeholder="请输入单位名称" disabled/></td>\n' +
                    '                        </tr>\n' +
                    '                        <tr>\n' +
                    '                            <td style="background:#ececec">纳税人识别码</td>\n' +
                    '                            <td><input class="canEdit text-c radius box-shadow" placeholder="请输入纳税人识别码" disabled/></td>\n' +
                    '                        </tr>\n' +
                    '                        <tr>\n' +
                    '                            <td style="background:#ececec;">注册地址</td>\n' +
                    '                            <td><input class="canEdit text-c radius box-shadow"  placeholder="请输入注册地址" disabled/></td>\n' +
                    '                        </tr>\n' +
                    '                        <tr>\n' +
                    '                            <td style="background:#ececec">注册电话</td>\n' +
                    '                            <td><input class="canEdit text-c radius box-shadow" placeholder="请输入注册电话" disabled/></td>\n' +
                    '                        </tr>\n' +
                    '                        <tr>\n' +
                    '                            <td style="background:#ececec">开户银行</td>\n' +
                    '                            <td><input class="canEdit text-c radius box-shadow" placeholder="请输入开户银行" disabled/></td>\n' +
                    '                        </tr>\n' +
                    '                        <tr>\n' +
                    '                            <td style="background:#ececec">银行账户</td>\n' +
                    '                            <td><input class="canEdit text-c radius box-shadow"  placeholder="请输入银行账户" disabled/></td>\n' +
                    '                        </tr>'
            }
            $("#specialinvoice").html(getInvoice)
    }
    web.doAjax(root.member.getInvoice+'?customerId='+customerId+'&invoiceType='+20+'', 'get', user_data, succCallBack);
}
//发票信息crm
function getInvoicecrm() { //获取普通发票信息
    var customerId = getQueryString('customerId');
    var getInvoicecrm=''
    var user_data = {}
    var succCallBack = function(data, status, response) {
        if(data.data!=""){
            for(var i=0;i<data.data.length;i++){
                getInvoicecrm+='<tr>\n' +
                    '                            <td class="w-300" style="background:#ececec;">单位名称</td>\n' +
                    '                            <td><input class="canEdit text-c radius box-shadow" placeholder="请输入单位名称" value="'+data.data[i].organizationName+'" disabled/></td>\n' +
                    '                        </tr>\n' +
                    '                        <tr>\n' +
                    '                            <td style="background:#ececec">纳税人识别码</td>\n' +
                    '                            <td><input class="canEdit text-c radius box-shadow"  placeholder="请输入纳税人识别码" value="'+data.data[i].taxpayerCode+'" disabled/></td>\n' +
                    '                        </tr>'
            }
        }else {
            getInvoicecrm='<tr>\n' +
                '                            <td class="w-300" style="background:#ececec;">单位名称</td>\n' +
                '                            <td><input class="canEdit text-c radius box-shadow" placeholder="请输入单位名称" disabled/></td>\n' +
                '                        </tr>\n' +
                '                        <tr>\n' +
                '                            <td style="background:#ececec">纳税人识别码</td>\n' +
                '                            <td><input class="canEdit text-c radius box-shadow"  placeholder="请输入纳税人识别码" disabled/></td>\n' +
                '                        </tr>'
        }
        $("#ordinaryinvoice").html(getInvoicecrm)
    }
    web.doAjax(root.member.getInvoice+'?customerId='+customerId+'&invoiceType='+10+'', 'get', user_data, succCallBack);
}
//查询门店信息
querystore();
function querystore() {
    var customerId = getQueryString('customerId');
    $.ajax({
        url:root.inter.findAddress,
        cache: false, //禁用缓存
        type: "POST",
        dataType: "json",
        data: {
            customerId:customerId,
            /*memberId:0*/

        },
        success: function (obj) {
            idufoijgo=obj
            if(obj.data!=null){
                if( obj.data.receiverList!=""){
                    $('#receivername').html(obj.data.receiverList[0].receiver_name);
                }




                $('#province_name').html(obj.data.province_name);

                var city_name=""
                if(obj.data.city_name!=null && obj.data.city_name!=""){
                    city_name=obj.data.city_name
                }else {
                    city_name=""
                }
                var area_name=""
                if(obj.data.area_name!=null && obj.data.city_name!=""){
                    area_name=obj.data.area_name
                }else {
                    area_name=""
                }
                var street_name=""
                if(obj.data.street_name!=null && obj.data.city_name!=""){
                    street_name=obj.data.street_name
                }else {
                    street_name=""
                }
                $('#detail_address').html(obj.data.province_name+city_name+area_name+street_name+obj.data.detail_address);
                $('#add_alias').html(obj.data.add_alias);
                $('#office_phone').html(obj.data.office_phone);
                $('#dzemail').html(obj.data.email);
                var handStr = '<td class="w-70">' +
                    '              <label class="form-label f-l" style="padding-left:22px">收货人：</label>' +
                    '          </td>';
                if(obj.data.receiverList && obj.data.receiverList.length>0){
                    $.each(obj.data.receiverList,function(k,v){
                        handStr+=
                            '                    <td class="w-60">' +
                            '                        <div class="row ml-10">' +
                            '                            <div class="">' +
                            '                                <span id="receiver_name">'+v.receiver_name+'</span>' +
                            '                            </div>' +
                            '                        </div>' +
                            '                    </td>' +
                            '                    <td class="w-180">' +
                            '                        <div class="row ml-10">' +
                            '                            <label class="form-label f-l">手机号码：</label>' +
                            '                            <div class="">' +
                            '                                <span id="mobile">'+v.mobile+'</span>' +
                            '                            </div>' +
                            '                        </div>' +
                            '                    </td>'


                    });
                }
            }
            $("#Consignee").html(handStr)

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });

}

function checkMaxInput(obj, maxLen) {
    if (obj == null || obj == undefined || obj == "") {
        return;
    }
    if (maxLen == null || maxLen == undefined || maxLen == "") {
        maxLen = 100;
    }

    var strResult;
    var $obj = $(obj);
    var newid = $obj.attr("id") + 'msg';
    var numsize= maxLen - obj.value.length;
    if (obj.value.length > maxLen) {	//如果输入的字数超过了限制
        obj.value = obj.value.substring(0, maxLen); //就去掉多余的字
        strResult = '<span  id="' + newid + '" style="position: relative;top: 20px;right: 95px;"><span>还能输入(' + numsize + ')字</span></span>'; //计算并显示剩余字数
    }
    else {
        strResult = '<span  id="' + newid + '" style="position: relative;top: 20px;right: 95px;"><span>还能输入(' + numsize + ')字</span></span>'; //计算并显示剩余字数
    }

    var $msg = $("#" + newid);
    if ($msg.length == 0) {
        $obj.after(strResult);
    }
    else {
        $msg.html("<span>还能输入("+numsize+")字</span>");
    }
}

//清空剩除字数提醒信息
function resetMaxmsg() {
    $("span.Max_msg").remove();
}

var isSave; // 1 ==> 是修改地址   2 ==> 是添加地址
//编辑地址弹框
function  invoEdit(addressBox) {
    //每次进来先清空一下
    $("#consigneename").val("");
    $("#consigneetelephone").val("");
    var handStr = "";
    $("#dizhi").modal("show");
    $("#dizhi").attr("data-shopid",addressBox);
    $(".addressTitle").html("编辑收货地址");
    var linkman = "";
    var moblie = "";
    var firstnameId;
    var secondnameId;
    // 查看地址信息
    var customerId = getQueryString('customerId');
    data = {
        customerId:customerId
    };
    var succCallBack = function (data, status, response){
        dizhiaa=data
        if (data.errorCode == "0"){
            if (null != data) {
                var addressPersonArr = data.data.receiverList;
                $("#addAlias").val(data.data.add_alias);
                $("#detailedAddress").val(data.data.detail_address);
                $("#landlineCelephone").val(data.data.office_phone);
                $("#email").val(data.data.email);
                if (addressPersonArr.length > 0){
                    for (var i = 0; i < addressPersonArr.length; i++){
                        handStr += '<tr style="margin-left: 30px">';
                        handStr += '<td style="text-align: left;padding-left:10px;width: 250px;"><span class="consigneename" style="display:inline-block;margin-left:45px;">姓名:<i>' + addressPersonArr[i].receiver_name + '</i></span></td>';
                        handStr += '<td style="text-align: left;padding-left: 5px;width: 186px;"><span style="text-align: left;display:block;" class="consigneetelephone">手机号码:<i>' + addressPersonArr[i].mobile + '</i></span></td>';
                        handStr += '<td><span class="consignee_id hide" >'+addressPersonArr[i].receiver_id+'</span></td>';
                        handStr += '<td><span class="consignee_status hide">'+addressPersonArr[i].status+'</span></td>';
                        handStr += '<td style="padding-left: 22px;"  onclick="Deletelinkman(this)"><a  href="javascript:;">删除</a></td>';

                        if(addressPersonArr[i].status !=10){
                            handStr += '<td style="padding-left: 22px;"><span>手机授权收货人无效，请重新选择</span></td>';
                        }else{
                            handStr += '<td style="padding-left: 22px;"><span></span></td>';
                        }
                        handStr += '</tr>';
                    }
                    $("#tableid").find("tbody").html(handStr);
                    handStr="";
                }

                $("#geta option:selected").html(data.data.province_name);
                $("#getb option:selected").html(data.data.city_name);
                $("#getc option:selected").html(data.data.area_name);
                $("#getd option:selected").html(data.data.street_name);
                $("#geta option:selected").val(data.data.province_id);
                $("#getb option:selected").val(data.data.city_id);
                $("#getc option:selected").val(data.data.district_id);
                $("#getd option:selected").val(data.data.street_id);

            }
        }
    };
    //修改地址时获取默认值
    web.doAjax(root.inter.findAddress, 'post', data, succCallBack);


    isSave = 1;
    return false;
}
//添加收货人名字和手机号
function addlinkman(id, ce){
    var addlink = $("#linkman").val();
    var addmobile = $("#mobilephone").val();
    var consigneeId = $("#consigneeId").val();
    var reg = /^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(147)|(145)|(166))\d{8}$/;

    if(addlink.replace(/^ +| +$/g,'')==''){
        $.Huimodalalert('收货人姓名不能为空', 2000);
        return false
    }
    if(addmobile.replace(/^ +| +$/g,'')==''){
        $.Huimodalalert('收货人手机号不能为空', 2000);
        return false
    }

    var nameReg = /^[\u4E00-\u9FA5]{2,5}$/;
    if(!nameReg.test(addlink)){
        $.Huimodalalert('收货人姓名只能为2到5位的汉字', 2000);
        return false;
    }

    if (addlink.length <= 0){   //验证收货人姓名不能为空
        $.Huimodalalert('收货人姓名不能为空', 2000);
        return false;
    } else if (addlink.length == 1){
        $.Huimodalalert('收货人姓名最少为两位', 2000);
        return false;

    } else if (addlink.length > 5){
        $.Huimodalalert('收货人姓名最多为五位', 2000);
        return false;
    }
    if (addmobile.length > 0 && (addmobile.length < 11 || !reg.test(addmobile))) {
        $.Huimodalalert('收货人手机号格式不正确', 2000);
        return;
    }
    var isTr = checkName(addlink,addmobile);
    addmobile = addmobile.length>1 ? addmobile : '---';
    if (isTr == true && addlink != null && addlink != ''){
        var handStr = '';
        handStr += '<tr style="margin-left: 30px">';
        handStr += '<td style=" text-align: left;padding-left:10px;width: 250px;"><span class="consigneename" style="display:inline-block;margin-left:45px;">姓名:<i>' + addlink + '</i></span></td>';
        handStr += '<td style="text-align: left;padding-left: 5px;width: 186px;"><span style="text-align: left;display:block;" class="consigneetelephone">手机号码:<i>' + addmobile + '</i></span></td>';
        handStr += '<td><span class="consignee_id hide" >' + consigneeId + '</span></td>';
        handStr += '<td><span class="consignee_status hide"></span></td>';
        handStr += '<td style="padding-left: 22px;"  onclick="Deletelinkman(this)"><a  href="javascript:;">删除</a></td>';
        handStr += '<td style="padding-left: 22px;"><span></span></td>';
        handStr += '</tr>';
        $("#tableid").find("table>tbody").append(handStr);
        $("#linkman").val('');
        $("input[name=mobilephone]").val('');
        $("#consigneeId").val('');
    }
}
//校验添加的收货人名字和手机号
function checkName(name,mob) {
    var flag = true;
    var arr = [];
    $('#tableid tbody tr').each(function (i, dom){
        arr.push({
            "name": $(dom).find('.consigneename').text().split(":")[1],
            "mobile": $(dom).find('.consigneetelephone').text().split(":")[1] == "---" ? "" : $(dom).find('.consigneetelephone').text().split(":")[1],
        });
        //手机号码和姓名不能重复
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].name == name) {
                $.Huimodalalert('该收货人已存在', 2000);
                flag = false;
            }
            if (mob.length > 0 && arr[i].mobile == mob) {
                $.Huimodalalert('该手机号码已存在', 2000);
                flag = false;
            }
        }
        if (arr.length >= 10) {
            $.Huimodalalert('最多可添加10个收货人', 2000);
            flag = false;
        }

    });
    return flag;
}
//删除授权收货人
function Deletelinkman(k) {
    $(k).parent().remove();
}


function closeodel() {
    $("#dizhi").modal("hide");
}
/*收货地址*/
initAddress()
function initAddress() {
    //初始化 省
    var user_data = {
        level:101,
        range:10
    }
    var succCallBack = function (data, status, response) {
        if(data.errorCode == 0){
            var tab_data=data.list;
            var cer = '';
            if(tab_data == ''){
                cer = '<option value=""></option>'
                $("#geta").html(cer);
            }else{
                cer = "<option value=''>请选择</option>"
                for(var i=0; i<tab_data.length; i++){
                    cer += '<option value="'+tab_data[i].address_id+','+tab_data[i].code+'">'+tab_data[i].name+'</option>'
                }
                $("#geta").html(cer);
            }
        }
    };
    web.doAjax(root.member.getLowerAddress,'post',user_data, succCallBack);

}
function discountdata (val, el) {

    if(el == 2){
        //市

        var special=$('#geta').val()
        var split = val.split(",");
        if(split[1]=="" || split[1]==undefined){
            var cer="<option value=''>请选择</option>"
            $("#getb").html(cer);
        }else {

            var user_data = {
                level: 102,
                parentCode: split[1]


            }
            var succCallBack = function (data, status, response) {
                strdata=data;
                if(data.errorCode=="0"){
                    var tab_data=data.list;
                    if(tab_data==''){
                        cer+='<option value=""></option>'
                        $("#getb").html(cer);
                    }else{
                        var cer="<option value=''>请选择</option>"
                        for(var i=0; i<tab_data.length; i++){
                            cer+='<option value="'+tab_data[i].address_id+','+tab_data[i].code+'">'+tab_data[i].name+'</option>'
                        }
                        $("#getb").html(cer);
                    }
                }
            };
            if(split[1] == 1 || split[1] == 2|| split[1] == 3 || split[1] == 4|| split[1] == 17|| split[1] == 32|| split[1] == 42|| split[1] == 43){
                $("#getd").hide();
            }else {
                $("#getd").show();
            }
            if (split[1] ==84){

                $("#getc").hide();
                $("#getd").hide();
            }else {
                $("#getc").show();
                $("#getd").show();
            }
            web.doAjax(root.member.getLowerAddress,'post',user_data, succCallBack);
        }
    } else if (el == 3) {
        var special=$('#geta').val()
        var split = val.split(",");
        if(special==""){
            var cer="<option value=''>请选择</option>"
            $("#getc").html(cer);
        }else {
            var user_data = {
                level: 103,
                parentCode:split[1]
            }
            var succCallBack = function (data, status, response) {
                if(data.errorCode=="0"){
                    var tab_data=data.list;
                    if(tab_data==''){
                        cer+='<option value=""></option>'
                        $("#getc").html(cer);
                    }else{
                        var cer="<option value=''>请选择</option>"
                        for(var i=0; i<tab_data.length; i++){
                            cer+='<option value="'+tab_data[i].address_id+','+tab_data[i].code+'">'+tab_data[i].name+'</option>'
                        }
                        $("#getc").html(cer);
                    }
                }
            };
            web.doAjax(root.member.getLowerAddress,'post',user_data, succCallBack);
        }
    } else if (el == 4) {
        var special=$('#geta').val()
        var split = val.split(",");
        if(special==""){
            var cer="<option value=''>请选择</option>"
            $("#getd").html(cer);
        }else {
            var user_data = {
                level: 104,
                parentCode: split[1]
            }
            var succCallBack = function (data, status, response) {
                if(data.errorCode=="0"){
                    var tab_data=data.list;
                    if(tab_data==''){
                        cer+='<option value=""></option>'
                        $("#getd").html(cer);
                    }else{
                        var cer="<option value=''>请选择</option>"
                        for(var i=0; i<tab_data.length; i++){
                            cer+='<option value="'+tab_data[i].address_id+','+tab_data[i].code+'">'+tab_data[i].name+'</option>'
                        }
                        $("#getd").html(cer);
                    }
                }
            };
            web.doAjax(root.member.getLowerAddress,'post',user_data, succCallBack);
        }
    }
}
//授权收货人关联
function myFuntion(){
    var linkman=$("#linkman").val();
    var user_data = {
        keywords:linkman,
        customerCode: OBJi.data.customerCode
    }
    var succCallBack = function (data, status, response) {
        kjshadkj =data
        if(data.errorCode=="0"){
            var jsonObj =data.consignee;
            if(jsonObj==""){
                $("#tudfan").html("<li>无数据</li> ");
            }else {
                var optionstring = "";
                for (var  i= 0; i < jsonObj.length; i++) {
                    optionstring += "<li onclick='relation("+ jsonObj[i].authorized_consignee_id+",\""+jsonObj[i].consignee_name+"\",\""+jsonObj[i].consignee_telephone+"\")' data-align=\"" + jsonObj[i].authorized_consignee_id + "\" > " + jsonObj[i].consignee_name + "</li>";
                }
                $("#tudfan").html(optionstring);
            }
        }else{
            $("#tudfan").html("<li>无数据</li> ");
        }
    }
    web.doAjax(root.replaceInter.replace_getConsigneeByCustomerCode,'post',user_data, succCallBack);
}
//授权收货人取光标
$("#linkman").focus(function () {
    $("#tudfan").show()
});
$(document).bind("click",function(e){
    //id为menu的是菜单，id为open的是打开菜单的按钮
    if($(e.target).closest("#tudfan").length == 0 && $(e.target).closest("#linkman").length == 0){
        //点击id为menu之外且id不是不是open，则触发
        $("#tudfan").hide()
    }
})
function relation(id,ce,tel) {
    $("#linkman").val(ce).text(id);
    $("#mobilephone").val(tel);
    $("#tudfan").hide()
}

//保存收货地址
function preservationarres() {
    /*var  phonei=$("#landlineCelephone").val();
    console.log(phonei)
    var reg= /^((0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/;
    if (!reg.test(phonei)) {
        layer.msg('请输入正确的固定电话', {icon: 6,time:1500});
        return false;

    }
    var  emailss=$("#email").val();
    var reg=/^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g;
    if (!reg.test(emailss)) {
        layer.msg('请输入正确的邮箱地址', {icon: 6,time:1500});
        return false;
    }*/

    var arr = [];
    var dsg="";
    if (idufoijgo.errorCode == 0) {
        $.each(dizhiaa.data.receiverList, function (k, v) {
            dsg = v
        })
        $('#tableid tbody tr').each(function (i, dom) {
            arr.push({
                "receiver_name": $(dom).find('.consigneename').find('i').text(),
                "mobile": $(dom).find('.consigneetelephone').find('i').text() == "---" ? "" : $(dom).find('.consigneetelephone').find('i').text(),
                'receiver_id': 0,
                "status": $(dom).find('.consignee_status').text().length > 0 ? $(dom).find('.consignee_status').text() : 10,
                "address_id": dsg.address_id,
            });
        });
        if($("#linkman").val()!="") {
            arr.push({
                "receiver_name": $("#linkman").val(),
                "mobile": $("#mobilephone").val(),
                'receiver_id': 0,
                "id": 0,
                "status": 10,
                "address_id": 0,
            });
        }
    } else {
        $('#tableid tbody tr').each(function (i, dom) {
            arr.push({
                "receiver_name": $(dom).find('.consigneename').find('i').text(),
                "mobile": $(dom).find('.consigneetelephone').find('i').text() == "---" ? "" : $(dom).find('.consigneetelephone').find('i').text(),
                'receiver_id': 0,
                "status": $(dom).find('.consignee_status').text().length > 0 ? $(dom).find('.consignee_status').text() : 10,
                "address_id": 0,
            });
        });
        if($("#linkman").val()!="") {
            arr.push({
                "receiver_name": $("#linkman").val(),
                "mobile": $("#mobilephone").val(),
                'receiver_id': 0,
                "id": 0,
                "status": 10,
                "address_id": 0,
            });
        }
    }

    //省份id
    var provinceaa =""
    if($("#geta").val()!=''){
        var provincea=$("#geta").val()
        var split = provincea.split(",");
        provinceaa =split[0]
    }else {
        provinceaa =dizhiaa.data.province_id
    }

    //城市id
    var citybb=""
    if($("#getb").val()!=''){
        var cityb=$("#getb").val()
        var split1 = cityb.split(",");
        citybb =split1[0]
    }else{
        $.Huimodalalert("请选择收货城市",2000);
        return false;
        /*citybb =dizhiaa.data.city_id*/
    }

    //区（县）id
    var districtcc=""
    if($("#getc").val()!=''){
        var districtc=$("#getc").val()
        var split2 = districtc.split(",");
        districtcc =split2[0]
    } else if($("#getc").val()==''){
        /*districtcc =dizhiaa.data.district_id*/
        $.Huimodalalert("请补充区县信息",2000);
        return false;
    }
    //街id
    var streetdd=""
    if($("#getd").val()!=''){
        var streetd=$("#getd").val()
        var split3 = streetd.split(",");
        streetdd =split3[0]
    }else {
        streetdd =0
        /* $.Huimodalalert("请补充街信息",2000);
         return false;*/
    }
    //省code
    var provincecode =""
    if($("#geta").val()!=''){
        var provincode=$("#geta").val()
        var split = provincode.split(",");
        provincecode =split[1]
    }

    //城市code
    var citycode=""
    if($("#getb").val()!=''){
        var citybs=$("#getb").val()
        var split1 = citybs.split(",");
        citycode =split1[1]
    }/*else {
        citycode =dizhiaa.data.city_code
    }*/

    //区（县）code
    var districtcode=""
    if($("#getc").val()!=''){
        var districtcd=$("#getc").val()
        var split2 = districtcd.split(",");
        districtcode =split2[1]
    }/*else {
        districtcode =dizhiaa.data.district_code
    }*/

    if($("#detailedAddress").val()==""){
        $.Huimodalalert("请填写详细地址",2000);
        return false;
    }


    var customerId = getQueryString('customerId');

    if(arr==""){
        $.Huimodalalert("至少填写一个收货人",2000);
        return false;
    }
    $.ajax({
        url: root.inter.saveAddress,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "customer_id":customerId,
            "member_id":"0",
            "province_id":provinceaa,
            "city_id":citybb,
            "district_id":districtcc,
            "street_id":streetdd,
            "province_code":provincecode,
            "is_default":"1",
            "receiverList":arr,
            "city_code":citycode,
            "district_code":districtcode,
            "detail_address":$("#detailedAddress").val().trim(),
            "add_alias":$("#addAlias").val().trim(),
            "office_phone":$("#landlineCelephone").val(),
            "email":$("#email").val(),
            "address_type":"10"

        }),
        success: function(obj){
            if(obj.errorCode==1){
                $.Huimodalalert(obj.msg,2000);
            }else {
                $("#dizhi").modal("hide");
                location.replace(location.href)
            }



        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });
}
//查询合同信息
customersee();
function customersee() {
    var id =getQueryString('id');
    var customerId = getQueryString('customerId');
    $.ajax({
        /*root.inter.findContractInfoByPage*/
        url: root.inter.findContractInfoByPage,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        data: {
            "pageNum":1,
            "pageSize":10,
            "customerId" :customerId,
            "customerCode":id

        },
        success: function (data) {
            var resuldata=data.data.result
            for(i=0; i<resuldata.length;i++){
                sessionStorage.setItem("contractNum",resuldata[i].contractNum);

            }

            customerlist1(data);
            $('.M-box3').pagination({
                pageCount: data.data.totalPage,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $.ajax({
                        /*root.inter.findContractInfoByPage*/
                        url: root.inter.findContractInfoByPage,
                        cache: false,  //禁用缓存
                        type: "POST",
                        dataType:'json',
                        data: {
                            "pageNum":1,
                            "pageSize":10,
                            "customerId" :customerId,
                            "customerCode":id

                        },
                        success: function (result) {
                            customerlist1(result);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });


        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
var dataSource = new Array();
var table;   //table对象
dataSource = [];
function customerlist1(data){
    dataSource.splice(0, dataSource.length);//清空数组
    var datashu =data.data.startIndex+1;
    var result=data.data.result
    $.each(result, function (i, field) {
        var datashus = datashu++
        var rowData = new Array();
        rowData.push(field.contractNum);
        rowData.push(field.oldSysContractNum);
        rowData.push(field.contractType);
        rowData.push(field.conStartDate);
        rowData.push(field.conEndDate);
        rowData.push(field.ftotalmount);
        rowData.push(field.credit);
        rowData.push(field.tickQuota);
        rowData.push(field.oldContractState);
        rowData.push(datashus);
        dataSource.push(rowData);
        rowData.push(field.customerCode);
        rowData.push(field.contractNum);

    });

    initData(dataSource);

    function initData(dataSource) {

        var dttable = $('#datatableq').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#datatableq").DataTable({
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": false,
            "retrieve": false,
            "destroy": false,
            "bAutoWidth": false,
            "bLengthChange": false,
            "aLengthMenu": [20],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },

                {
                    "render": function (data, type, row, meta) {
                        var val = row[9]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[0]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 1
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[1]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 2
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[2]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 3
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[3]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 4
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[4]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 5
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[5]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 6
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[6]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 7
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[7]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 8
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[8]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 9
                },

                {
                    "render": function (data, type, row, meta) {

                        if(row[2]=='购销协议'){
                            var val = '<a class="powerButton 243"><span class="list"  onclick="detail(\'合同详情\',\'../contract/contr_detail.html?customerCode=' + row[10] + '&contractNum=' + row[11] + '\')">查看</span></a></div>';
                            return val;
                        }else if(row[2]=='虚拟合同'){
                            var val = '<a class="powerButton 243"><span class="list"  onclick="detail(\'合同详情\',\'../contract/xuni_detail.html?customerCode=' + row[10] + '&contractNum=' + row[11] + '\')">查看</span></a></div>';
                            return val;
                        }else if(row[2]=='单笔合同'){
                            var val = '<a class="powerButton 243"><span class="list"  onclick="detail(\'合同详情\',\'../contract/dan_detail.html?customerCode=' + row[10] + '&contractNum=' + row[11] + '\')">查看</span></a></div>';
                            return val;
                        }if(row[2]=='客户资信调查表'){
                            var val = '<a class="powerButton 243"><span class="list"  onclick="detail(\'合同详情\',\'../contract/contr_detail.html?customerCode=' + row[10] + '&contractNum=' + row[11] + '\')">查看</span></a></div>';

                            return val;
                        }


                        return val;
                    },
                    "targets":10
                }


            ]
        });
//权限控制函数
        power()
    };
}
function detail(title, url) {
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}

//查询关联额度控制
customerseetoo();
function customerseetoo() {
    var id =getQueryString('id');
    var customerId = getQueryString('customerId');
    $.ajax({
        /*root.inter.queryCustomerLimitInfo*/
        url: root.inter.queryCustomerLimitInfo,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        data: {
            "customerCode":id

        },
        success: function (data) {
            customertoo1(data.data);
            $('.M-box3').pagination({
                pageCount: data.data.totalPage,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $.ajax({
                        /*root.inter.findContractInfoByPage*/
                        url: root.inter.findContractInfoByPage,
                        cache: false,  //禁用缓存
                        type: "POST",
                        dataType:'json',
                        data: {
                            "customerCode":id

                        },
                        success: function (result) {
                            customertoo1(result.data);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });


        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
var dataSource = new Array();
var table;   //table对象
dataSource = [];
function customertoo1(data){
    dataSource.splice(0, dataSource.length);//清空数组

    var result=data.parent[0]?data.parent[0].customer_name:data.own[0].customer_name
    var resultsss=data.son

    var results=data.own
    var a=[]
    $.each(resultsss, function (i, v) {
        if(v.contractInfo){
            a.push(v)
        }
    });
    /*if(results[0].contractInfo){
        a.push(results[0])
    }*/
    $.each(a, function (i, field2) {
        var rowData = new Array();
        if(field2.contractInfo){
            rowData.push(result);
            rowData.push(field2.customer_name);//子客户名称
            rowData.push(field2.contractInfo.contractType);
            rowData.push(field2.contractInfo.oldContractState);
            rowData.push(field2.contractInfo.ftotalmount);
            rowData.push(field2.contractInfo.credit);
            rowData.push(field2.contractInfo.tickQuota);
            rowData.push(field2.contractInfo.fkztypename);
            rowData.push(field2.contractInfo.threshold);
            rowData.push(field2.contractInfo.availableQuota);
        }

        dataSource.push(rowData);
    });


    initData(dataSource);

    function initData(dataSource) {

        var dttable = $('#datatablet').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#datatablet").DataTable({
            // "order": false,
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": false,
            "retrieve": false,
            "destroy": false,
            "bAutoWidth": false,
            "bLengthChange": false,
            "aLengthMenu": [20],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },

                {
                    "render": function (data, type, row, meta) {
                        var val = row[0]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 0
                },

                {
                    "render": function (data, type, row, meta) {
                        var val = row[1]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 1
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[2]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 2
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[3]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 3
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[4]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 4
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[5]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 5
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[6]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 6
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[7]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 7
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[8]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 8
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[9]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 9
                },
            ]
        });

    };
}

//修改客户别名
function aliasupdata() {
    $(".customerAliasName").removeAttr("readonly");

    $(".customerAliasName2").css({
        display: "inline"
    });
    $(".customerAliasName1").css({
        display: "none"
    });
}
function aliasCancel() {
    $(".customerAliasName").attr("readonly", "readonly");

    $(".customerAliasName2").css({
        display: "none"
    });
    $(".customerAliasName1").css({
        display: "inline"
    });
}
function aliasupdataSure(type) {
    var names=""
if(type==1){
   names= $("#name1").val()
}else {
    names= $("#name2").val()
}
    $.ajax({
        url:root.inter.updateCustomerInfoByCode,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        async:false,
        data: {
            customerCode:customerdata,
            operateManagerId:"",
            operateManagerName:"",
            groupBusinessLicenseAddr:"",
            groupOpeningAccountAddr:"",
            groupLoa:"",
            groupIDcardUrl:"",
            purchGoodIntroduct:"",
            email:"",
            customerAliasName:names
        },
        success: function (data) {
            $(".customerAliasName").attr("readonly", "readonly");

            $(".customerAliasName2").css({
                display: "none"
            });
            $(".customerAliasName1").css({
                display: "inline"
            });
            location.replace(location.href)
        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    })

}
//运费规则展示
function freightshow(val) {
        //收取运费
    if(val==10){
        $("#zhanshi").css({
            display: "none"
        });
        $("#freight_by_ladder").css({
            display: "none"
        });
    }else if(val==20){
        //免运费
        $("#zhanshi").css({
            display: "block"
        });
        $("#freight_by_ladder").css({
            display: "none"
        });
    }else if(val==30){
       //阶梯运费
        $("#zhanshi").css({
            display: "none"
        });
        $("#freight_by_ladder").css({
            display: "block"
        });
    }
}
/*
运费规则*/
function updatafreight() {
    if(sessionStorage.getItem("customertype")=='商店'){
        /*$.Huimodalalert('分销客户免运费！',2000);*/
        $("#updatafreight").modal("show");
        var customerId = getQueryString('customerId');
        $.ajax({
            type: "POST",
            url: root.member.getCustomerFreightDetail,
            cache: false,  //禁用缓存
            dataType: "json",
            data: {
                customerId: customerId
            },
            success: function (result) {
                //运费规则
                if(result.data.freightRule!=null){
                    if(result.data.freightRule==10){
                        $("input[type='radio'][name='Freightrules']").get(0).checked = true
                        $("#zhanshi").css({
                            display: "none"
                        });
                        $("#freight_by_ladder").css({
                            display: "none"
                        });
                    }else if(result.data.freightRule==20) {
                        $("input[type='radio'][name='Freightrules']").get(1).checked = true
                        $("#zhanshi").css({
                            display: "block"
                        });
                        $("#freight_by_ladder").css({
                            display: "none"
                        });
                    }else if(result.data.freightRule==30) {
                        $("input[type='radio'][name='Freightrules']").get(2).checked = true
                        $("#zhanshi").css({
                            display: "none"
                        });
                        $("#freight_by_ladder").css({
                            display: "block"
                        });
                    }else if(result.data.freightRule==40) {
                        $("input[type='radio'][name='Freightrules']").get(3).checked = true
                        $("#zhanshi").css({
                            display: "none"
                        });
                        $("#freight_by_ladder").css({
                            display: "none"
                        });
                    }
                }else {
                    $("input[type='radio'][name='Freightrules']").get(1).checked = true
                    $("#zhanshi").css({
                        display: "block"
                    });
                    $("#freight_by_ladder").css({
                        display: "none"
                    });
                }
                //平台免运费政策是否可以点击
                if(result.data.freightStatus==0){
                    $("#limsitss").removeAttr("disabled")
                    $("#limsitss").removeAttr("style")
                }else {
                    $("#limsitss").attr("disabled","disabled")
                    $("#limsitss").attr("style","appearance: auto;")

                }

                //配送方式
                var deliveryWay = document.getElementsByName("deliveryWay");
                if (result.data.deliveryWay != ""&&result.data.deliveryWay != null) {
                        var deliveryWayList = result.data.deliveryWay.split(",");
                        for (k in deliveryWay) {
                            for (var i = 0; i < deliveryWayList.length; i++) {
                                if (deliveryWay[k].value == deliveryWayList[i]) {
                                    deliveryWay[k].checked = true;
                                }
                            }
                        }
                }else {
                    for (k in deliveryWay) {
                                deliveryWay[k].checked = true;
                    }
                }

                var all_check_num = $("input[name='deliveryWay']:checked").length;
                var deliveryWay_num = $("input[name='deliveryWay']").length;
                $("#deliveryWay-all").prop("checked",all_check_num == deliveryWay_num);

                //范围
                var regionhtml = '';//表格
                var Twolevel =""//二级
                var Threelevel=""//三级
                var freightInfoDtoMapList=result.data.freightInfoDtoMap;

                for ( key in freightInfoDtoMapList){
                    if(freightInfoDtoMapList[key].length >0){
                        regionhtml +='  <tr>\n'
                        regionhtml +=    ' <td class="td1" rowspan=" '+freightInfoDtoMapList[key].length+ ' " >'+key+'</td>\n'
                        $.each(freightInfoDtoMapList[key],function (i,item) {

                            regionhtml +=    '<td class="td2" ><input class="isclicks" onclick="Provincialelection(this)"  type="checkbox" value="'+item.provinceCode+'">'+item.provinceName+'</td>\n'
                            regionhtml +=   ' <td class="td3">\n'
                            if(item.provinceCode==1||item.provinceCode==2||item.provinceCode==3||item.provinceCode==4){//如果是直辖市隐藏市级
                                $.each(item.cityDtos,function (j,itm) {
                                    if(result.data.freightRule!=null){
                                    if(itm.isContain==true){
                                        regionhtml +=   '<input class="isclick hide" onclick="checkeds()" type="checkbox" checked value="'+itm.code+'"><span class="hide">'+itm.name+'</span>\n'

                                    }else {
                                        regionhtml +=   '<input class="isclick hide" onclick="checkeds()" type="checkbox" value="'+itm.code+'"><span class="hide">'+itm.name+'</span>\n'

                                    }
                                    }else {
                                        regionhtml +=   '<input class="isclick hide" onclick="checkeds()" type="checkbox" checked value="'+itm.code+'"><span class="hide">'+itm.name+'</span>\n'

                                    }
                                })
                            }else {
                                $.each(item.cityDtos,function (j,itm) {
                                    if(result.data.freightRule!=null) {
                                        if (itm.isContain == true) {
                                            regionhtml += '<input class="isclick" onclick="checkeds()" checked type="checkbox" value="' + itm.code + '">' + itm.name + '\n'

                                        } else {
                                            regionhtml += '<input class="isclick" onclick="checkeds()" type="checkbox" value="' + itm.code + '">' + itm.name + '\n'

                                        }
                                    }else {
                                        regionhtml += '<input class="isclick" onclick="checkeds()" checked type="checkbox" value="' + itm.code + '">' + itm.name + '\n'

                                    }
                                })
                            }
                            regionhtml +=    ' </td>\n'
                            regionhtml +=    ' </tr>'
                        })


                    }
                }
                $("#Range").html(regionhtml)
                checkeds()
                //阶梯设置
                $("#thresholdFreight").val(result.data.ladderThresholdMoney)
                var freight_by_laddertable = ""
                if(result.data.feightLadderInfoDtos!=null&&result.data.feightLadderInfoDtos!=""){
                    var feightLadderInfoDtosall= result.data.feightLadderInfoDtos;
                    for (var h = 0; h < feightLadderInfoDtosall.length; h++) {
                        if(feightLadderInfoDtosall[h].level==1){
                            freight_by_laddertable += '<tr>' +
                                '                            <td class="freight_1">'+feightLadderInfoDtosall[h].level+'</td>' +
                                '                               <td class="freight_2">订单商品金额满<input type="text" class="input-text mr-5"  style="width: 43px;" disabled="disabled" value="'+feightLadderInfoDtosall[h].orderMoney+'">元</td>' +
                                '                                    <td class="freight_3">运费<input type="text" class="input-text mr-5" oninput="value=value.replace(/[^\\d]/g,\'\')" maxlength="4" style="width: 43px;" value="'+feightLadderInfoDtosall[h].freightMoney+'">元</td>' +
                                '                                    <td class="freight_4"></td>' +
                                '                    </tr>'
                        }else {
                            freight_by_laddertable += '<tr>' +
                                '                            <td class="freight_1">'+feightLadderInfoDtosall[h].level+'</td>' +
                                '                               <td class="freight_2">订单商品金额满<input type="text" class="input-text mr-5"  oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')" style="width: 43px;"  value="'+feightLadderInfoDtosall[h].orderMoney+'">元</td>' +
                                '                                    <td class="freight_3">运费<input type="text" class="input-text mr-5" oninput="value=value.replace(/[^\\d]/g,\'\')" maxlength="4" style="width: 43px;" value="'+feightLadderInfoDtosall[h].freightMoney+'">元</td>' +
                                '                                    <td class="freight_4"><a class="delProduct" onclick="deletes(this)">删除</a></td>' +
                                '                    </tr>'
                        }

                    }
                }else {
                    freight_by_laddertable += '<tr>' +
                        '                            <td class="freight_1">1</td>' +
                        '                               <td class="freight_2">订单商品金额满<input type="text" class="input-text mr-5" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')"  style="width: 43px;" disabled="disabled" value="0">元</td>' +
                        '                                    <td class="freight_3">运费<input type="text" class="input-text mr-5" oninput="value=value.replace(/[^\\d]/g,\'\')" maxlength="4" style="width: 43px;" value="">元</td>' +
                        '                                    <td class="freight_4"></td>' +
                        '                    </tr>'
                }

                $(".freight_by_ladders").html(freight_by_laddertable);
            },
            error: function () {
                $.Huimodalalert('失败！',2000);
            }
        });
    }else {
        $("#updatafreight").modal("show");
        var customerId = getQueryString('customerId');
        $.ajax({
            type: "POST",
            url: root.member.getCustomerFreightDetail,
            cache: false,  //禁用缓存
            dataType: "json",
            data: {
                customerId: customerId
            },
            success: function (result) {
                //运费规则
                if(result.data.freightRule!=null){
                    if(result.data.freightRule==10){
                        $("input[type='radio'][name='Freightrules']").get(0).checked = true
                        $("#zhanshi").css({
                            display: "none"
                        });
                        $("#freight_by_ladder").css({
                            display: "none"
                        });
                    }else if(result.data.freightRule==20) {
                        $("input[type='radio'][name='Freightrules']").get(1).checked = true
                        $("#zhanshi").css({
                            display: "block"
                        });
                        $("#freight_by_ladder").css({
                            display: "none"
                        });
                    }else if(result.data.freightRule==30) {
                        $("input[type='radio'][name='Freightrules']").get(2).checked = true
                        $("#zhanshi").css({
                            display: "none"
                        });
                        $("#freight_by_ladder").css({
                            display: "block"
                        });
                    }else if(result.data.freightRule==40){
                        $("input[type='radio'][name='Freightrules']").get(3).checked = true
                        $("#zhanshi").css({
                            display: "none"
                        });
                        $("#freight_by_ladder").css({
                            display: "none"
                        });
                    }
                }else {
                    $("input[type='radio'][name='Freightrules']").get(0).checked = true
                    $("#zhanshi").css({
                        display: "none"
                    });
                }
                //平台免运费政策是否可以点击
                if(result.data.freightStatus==0){
                    $("#limsitss").removeAttr("disabled")
                    $("#limsitss").removeAttr("style")
                }else {
                    $("#limsitss").attr("disabled","disabled")
                    $("#limsitss").attr("style","appearance: auto;")

                }

                //配送方式
                var deliveryWay = document.getElementsByName("deliveryWay");
                if (result.data.deliveryWay != ""&&result.data.deliveryWay != null) {
                    if(result.data.deliveryWay != null){
                        var deliveryWayList = result.data.deliveryWay.split(",");
                        for (k in deliveryWay) {
                            for (var i = 0; i < deliveryWayList.length; i++) {
                                if (deliveryWay[k].value == deliveryWayList[i]) {
                                    deliveryWay[k].checked = true;
                                }
                            }
                        }
                    }

                }

                //范围
                var regionhtml = '';//表格
                var Twolevel =""//二级
                var Threelevel=""//三级
                var freightInfoDtoMapList=result.data.freightInfoDtoMap;

                for ( key in freightInfoDtoMapList){
                    if(freightInfoDtoMapList[key].length >0){
                        regionhtml +='  <tr>\n'
                        regionhtml +=    ' <td class="td1" rowspan=" '+freightInfoDtoMapList[key].length+ ' " >'+key+'</td>\n'
                        $.each(freightInfoDtoMapList[key],function (i,item) {

                            regionhtml +=    '<td class="td2" ><input class="isclicks" onclick="Provincialelection(this)"  type="checkbox" value="'+item.provinceCode+'">'+item.provinceName+'</td>\n'
                            regionhtml +=   ' <td class="td3">\n'
                            if(item.provinceCode==1||item.provinceCode==2||item.provinceCode==3||item.provinceCode==4){//如果是直辖市隐藏市级
                                $.each(item.cityDtos,function (j,itm) {

                                    if(itm.isContain==true){
                                        regionhtml +=   '<input class="isclick hide" onclick="checkeds()" type="checkbox" checked value="'+itm.code+'"><span class="hide">'+itm.name+'</span>\n'

                                    }else {
                                        regionhtml +=   '<input class="isclick hide" onclick="checkeds()" type="checkbox" value="'+itm.code+'"><span class="hide">'+itm.name+'</span>\n'

                                    }
                                })
                            }else {
                                $.each(item.cityDtos,function (j,itm) {
                                    if(itm.isContain==true){
                                        regionhtml +=   '<input class="isclick" onclick="checkeds()" checked type="checkbox" value="'+itm.code+'">'+itm.name+'\n'

                                    }else {
                                        regionhtml +=   '<input class="isclick" onclick="checkeds()" type="checkbox" value="'+itm.code+'">'+itm.name+'\n'

                                    }
                                })
                            }
                            regionhtml +=    ' </td>\n'
                            regionhtml +=    ' </tr>'
                        })


                    }
                }
                $("#Range").html(regionhtml)
                checkeds()
                //阶梯设置
                $("#thresholdFreight").val(result.data.ladderThresholdMoney)
                var freight_by_laddertable = ""
                if(result.data.feightLadderInfoDtos!=null&&result.data.feightLadderInfoDtos!=""){
                    var feightLadderInfoDtosall= result.data.feightLadderInfoDtos;
                    for (var h = 0; h < feightLadderInfoDtosall.length; h++) {
                        if(feightLadderInfoDtosall[h].level==1){
                            freight_by_laddertable += '<tr>' +
                                '                            <td class="freight_1">'+feightLadderInfoDtosall[h].level+'</td>' +
                                '                               <td class="freight_2">订单商品金额满<input type="text" class="input-text mr-5" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')"  style="width: 43px;" disabled="disabled" value="'+feightLadderInfoDtosall[h].orderMoney+'">元</td>' +
                                '                                    <td class="freight_3">运费<input type="text" class="input-text mr-5" oninput="value=value.replace(/[^\\d]/g,\'\')" maxlength="4" style="width: 43px;" value="'+feightLadderInfoDtosall[h].freightMoney+'">元</td>' +
                                '                                    <td class="freight_4"></td>' +
                                '                    </tr>'
                        }else {
                            freight_by_laddertable += '<tr>' +
                                '                            <td class="freight_1">'+feightLadderInfoDtosall[h].level+'</td>' +
                                '                               <td class="freight_2">订单商品金额满<input type="text" class="input-text mr-5" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')"  style="width: 43px;"  value="'+feightLadderInfoDtosall[h].orderMoney+'">元</td>' +
                                '                                    <td class="freight_3">运费<input type="text" class="input-text mr-5" oninput="value=value.replace(/[^\\d]/g,\'\')" maxlength="4" style="width: 43px;" value="'+feightLadderInfoDtosall[h].freightMoney+'">元</td>' +
                                '                                    <td class="freight_4"><a class="delProduct" onclick="deletes(this)">删除</a></td>' +
                                '                    </tr>'
                        }

                    }
                }else {
                    freight_by_laddertable += '<tr>' +
                        '                            <td class="freight_1">1</td>' +
                        '                               <td class="freight_2">订单商品金额满<input type="text" class="input-text mr-5" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')" style="width: 43px;" disabled="disabled" value="0">元</td>' +
                        '                                    <td class="freight_3">运费<input type="text" class="input-text mr-5" oninput="value=value.replace(/[^\\d]/g,\'\')" maxlength="4" style="width: 43px;" value="">元</td>' +
                        '                                    <td class="freight_4"></td>' +
                        '                    </tr>'
                }

                $(".freight_by_ladders").html(freight_by_laddertable);
            },
            error: function () {
                $.Huimodalalert('失败！',2000);
            }
        });
    }


}

function close_updatafreight() {
    $("#updatafreight").modal("hide")
}
//全选全不选
function stoprop() {
    if($("#nolimsidst").is(':checked')==true){
        //全选
        //市
        var isclick =$(".isclick")
        for(var i = 0; i < isclick.length; i++) {
            isclick[i].checked = true;
        }
        //省
        var isclicks =$(".isclicks")
        for(var i = 0; i < isclicks.length; i++) {
            isclicks[i].checked = true;
        }
    }else {
        //全不选
        var isclick =$(".isclick")
        for(var i = 0; i < isclick.length; i++) {
            isclick[i].checked = false;
        }
        //省
        var isclicks =$(".isclicks")
        for(var i = 0; i < isclicks.length; i++) {
            isclicks[i].checked = false;
        }
    }


}
//市级全部选中省自动选中
function checkeds(){
    $('#Range tr').each(function (index, Range) {
        if($(Range).find(".isclick").is(":checked")==true){
            if($(Range).find(".isclick:checked").length==$(Range).find(".isclick").length){
                $(Range).find(".isclicks").prop("checked", true);
            }else {

                $(Range).find(".isclicks").prop("checked", false);
            }
        }else {
            $(Range).find(".isclicks").prop("checked", false);
        }

    })
    var isclick =$(".isclick")
    var isclicks =$(".isclick:checked")
    if(isclicks.length==isclick.length){
        $("#nolimsidst").prop("checked", true)
    }else {
        $("#nolimsidst").prop("checked", false)
    }

}
//省选中市级自动全选中
function Provincialelection(val) {
    for (var i = 0; i < $(val).parent().parent().find('.isclick').length; i++) {
                if($(val).parent().find('.isclicks').is(":checked")==true){
                    $(val).parent().parent().find('.isclick')[i].checked=true
                }else {
                    $(val).parent().parent().find('.isclick')[i].checked=false
                }


    }
    var isclick =$(".isclicks")
    var isclicks =$(".isclicks:checked")
    if(isclicks.length==isclick.length){
        $("#nolimsidst").prop("checked", true)
    }else {
        $("#nolimsidst").prop("checked", false)
    }

}


//添加层级
var coner=10
function add_freight_by_ladder() {
    var addfreight_by_ladder= ""
    var hierarchy=$('.freight_by_ladders tr').length+1
    addfreight_by_ladder += '<tr>' +
        '                            <td class="freight_1">'+hierarchy+'</td>' +
        '                               <td class="freight_2">订单商品金额满<input type="text" class="input-text mr-5" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')" style="width: 43px;" value="">元</td>' +
        '                                    <td class="freight_3">运费<input type="text" class="input-text mr-5" oninput="value=value.replace(/[^\\d]/g,\'\')" maxlength="4" style="width: 43px;" value="">元</td>' +
        '                                    <td class="freight_4"><a class="delProduct" onclick="deletes(this)">删除</a></td>' +
        '                    </tr>'

    if($('.freight_by_ladders tr').length<coner){
        $(".freight_by_ladders").append(addfreight_by_ladder);
    }else {
        layer.msg('最多添加10级！', {icon: 5, time: 1000});
    }
}
//删除
function deletes(obj){
    var curIndk = layer.confirm('确定要删除吗？', {closeBtn:false,title:'提示',btn: ['确定', '取消']}, function(index){
        $(obj).parents("tr").remove();
        numCheck()
        layer.close(curIndk);
    },function(){
        layer.close(curIndk);
    });

};
//层级，删除后自动改变层级
function numCheck(){
    var num = $('.freight_by_ladders tr').length;     //获取行数
    for (var i = 0; i <= num; i++) {         //进行循环
        $('.freight_by_ladders tr .freight_1').eq(i).html(i+1);
    };
}




//保存

function Freightadd() {
    var freightInfoDtosarr=[]
    var  freightInfoDtos={}
    var ff=[]
    var customerId = getQueryString('customerId');

    //配送方式
    var deliveryWays = "";
    if($("input[name='Freightrules']:checked").val()==20){
        var deliveryWay =  $("input[name='deliveryWay']");
        for (var i = 0; i < deliveryWay.length; i++) {
            if(deliveryWay[i].checked){
                deliveryWays +=deliveryWay[i].value+ ",";
            }
        }
        //去掉最后一个逗号(如果不需要去掉，就不用写)
        if (deliveryWays.length > 0) {
            deliveryWays = deliveryWays.substr(0, deliveryWays.length - 1);
        }
    }else {
        deliveryWays = ""
    }

    //范围
    if($("input[name='Freightrules']:checked").val()==20){
        var areaTr = $('#Range tr');
        for(var i=0;i<areaTr.length;i++){
            // console.log($(areaTr[i]).find(".td3"))
            if($(areaTr[i]).find(".td2 .isclicks：checked")&&($(areaTr[i]).find(".td2 .isclicks").val()==1||$(areaTr[i]).find(".td2 .isclicks").val()==2||$(areaTr[i]).find(".td2 .isclicks").val()==3||$(areaTr[i]).find(".td2 .isclicks").val()==4)){
                if($(areaTr[i]).find(".td2 .isclicks：checked")){
                    var cityCodeArr = [];
                    if($(areaTr[i]).find(".td3 .isclick")&&$(areaTr[i]).find(".td3 .isclick").length>0){
                        for (var j=0;j<$(areaTr[i]).find(".td3 .isclick").length;j++){
                            var t3CheckedInp = $(areaTr[i]).find(".td3 .isclick")[j];
                            if($(t3CheckedInp).prop("checked")){
                                cityCodeArr.push({
                                    code:$(t3CheckedInp).val()
                                })
                            }
                        }
                    }
                    if(cityCodeArr.length>0){
                        freightInfoDtos={
                            provinceCode:$(areaTr[i]).find(".td2 .isclicks").val(),
                            cityDtos:cityCodeArr
                        }
                        freightInfoDtosarr.push(freightInfoDtos);
                    }
                }
            }else {
                var cityCodeArr = [];
                if($(areaTr[i]).find(".td3 .isclick")&&$(areaTr[i]).find(".td3 .isclick").length>0){
                    for (var j=0;j<$(areaTr[i]).find(".td3 .isclick").length;j++){
                        var t3CheckedInp = $(areaTr[i]).find(".td3 .isclick")[j];
                        if($(t3CheckedInp).prop("checked")){
                            cityCodeArr.push({
                                code:$(t3CheckedInp).val()
                            })
                        }
                    }
                }
                if(cityCodeArr.length>0){
                    freightInfoDtos={
                        provinceCode:$(areaTr[i]).find(".td2 .isclicks").val(),
                        cityDtos:cityCodeArr
                    }
                    freightInfoDtosarr.push(freightInfoDtos);
                }
            }
        }
    }else {
        freightInfoDtosarr=[]
    }
    if ($("input[name='Freightrules']:checked").val()==20) {
        if(deliveryWays==""){
            $.Huimodalalert('请选择配送方式！',2000);
            return false;
        }
        if(freightInfoDtosarr==""){
            $.Huimodalalert('请选择范围！',2000);
            return false;
        }
    }

    //阶梯运费
    var feightLadderInfoDtos = $('.freight_by_ladders tr');
    var feightLadderInfoDtosarr=[]
    var plm={}
    if ($("input[name='Freightrules']:checked").val()==30) {
            if($("#thresholdFreight").val()==""){
                $.Huimodalalert('使用阶梯门槛不能为空！',2000);
                return false
            }
        for (var j = 0; j < feightLadderInfoDtos.length; j++) {
            if($(feightLadderInfoDtos[j]).find('.freight_2 input').val()==""){
                $.Huimodalalert('请填写订单商品金额',2000);
                return false
            }
            if($(feightLadderInfoDtos[j]).find('.freight_3 input').val()==""){
                $.Huimodalalert('请填写运费金额',2000);
                return false
            }
            plm = {
                "level": $(feightLadderInfoDtos[j]).find('.freight_1').text(),
                "orderMoney": $(feightLadderInfoDtos[j]).find('.freight_2 input').val(),
                "freightMoney": $(feightLadderInfoDtos[j]).find('.freight_3 input').val()

            }
            feightLadderInfoDtosarr.push(plm)
        }
        if($('.freight_by_ladders tr').length==3) {
            if (Number(feightLadderInfoDtosarr[1].orderMoney) == Number(feightLadderInfoDtosarr[2].orderMoney)) {
                $.Huimodalalert('订单商品金额不能相同', 2000);
                return false;

            }
            console.log(feightLadderInfoDtosarr)

            if (Number(feightLadderInfoDtosarr[2].orderMoney)  < Number(feightLadderInfoDtosarr[1].orderMoney)) {
                $.Huimodalalert('下一层级金额需大于上一层级', 2000);
                return false;

            }
        }

    }
        var ladderThresholdMoneys=""
    if($("input[name='Freightrules']:checked").val()==30){
        ladderThresholdMoneys=$("#thresholdFreight").val()
    }else {
        ladderThresholdMoneys=""
    }

    $.ajax({
        url:root.member.saveCustomerFreight,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "customerId":customerId,
            "freightRule":$("input[name='Freightrules']:checked").val(),
            "deliveryWay":deliveryWays,
            "freightInfoDtos":freightInfoDtosarr,
            "feightLadderInfoDtos":feightLadderInfoDtosarr,
            "ladderThresholdMoney":ladderThresholdMoneys,
            "operateUserId": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
            "operateUserName": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name

        }),
        success: function (data) {
            if(data.errorCode==0){
                layer.msg("修改成功！", {
                    icon: 1,
                    time: 1000
                }, function() {
                    $("#updatafreight").modal("hide")
                    getCustomerSetting();
                    // location.replace(location.href)
                });

            }else {
                $.Huimodalalert(data.msg,2000);
            }
        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });

}

//支付方式

$("[name='paymentmethod']").click(function () { //多选框点击选中
    if($(".paymentmethod:checked").length==0){
        $.Huimodalalert('最少保留一种支付方式！',2000);
        var paymentMethods = document.getElementsByName("paymentmethod");
        if (paymentMethodalls != ""&&paymentMethodalls!= null) {
            var paymentMethodList = paymentMethodalls.split(",");
            for (k in paymentMethods) {
                for (var i = 0; i < paymentMethodList.length; i++) {
                    if (paymentMethods[k].value == paymentMethodList[i]) {
                        paymentMethods[k].checked = true;
                    }
                }
            }
        }else {
            for (k in paymentMethods) {

                paymentMethods[k].checked = true;

            }
        }

    }else {
        insertChangeInfo()
    }
});

function saveCustomerNeedReceipt(needReceipt){
    var id =getQueryString('id');
    var customerId = getQueryString('customerId');
    var param = {
        customerId:customerId,
        needReceipt:needReceipt
    };
    $.ajax({
        url: root.member.saveCustomerNeedReceipt,
        cache: false, //禁用缓存
        type: "POST",
        dataType:"json",
        data:param,
        success: function(obj){
            $.Huimodalalert(obj.data,2000);
        }
    })
}
